package com.itrui.user.web;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itrui.user.common.R;
import com.itrui.user.pojo.Business;
import com.itrui.user.service.BusinessService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Random;

/**
 * 模块：商家
 * 功能：登录注册，修改信息
 */
@Slf4j
@RestController
@RequestMapping("/business")
public class BusinessController {

    @Autowired
    private BusinessService businessService;

    @PostMapping
    public R<Business> login(@RequestBody Business business){
        LambdaQueryWrapper<Business> queryWrapper = new LambdaQueryWrapper<>();
        //当前商家数据库是否存在
        queryWrapper.eq(Business::getAccount, business.getAccount());
        Business one = businessService.getOne(queryWrapper);
        //存在，查看登录状态
        if (one != null){
            if (one.getStatus() == 0){
                //登录验证
                if (business.getPassword().equals(one.getPassword())){
                    one.setStatus(1);
                    businessService.update(one, queryWrapper);
                    return R.success(one);
                }else {
                    return R.error("密码错误");
                }
            }else {
                //已登录，返回错误
                return R.error("不能重复登录");
            }
        }else {
            //不存在，注册
            Random random = new Random();
            business.setName("易易商家"+random.nextInt());
            business.setCreateTime(LocalDateTime.now());
            boolean save = businessService.save(business);
            return save?R.success(business):R.error("注册失败");
        }
    }
    ;

    @PutMapping
    public R<String> ModifyUserInfo(@RequestBody Business business) {
        System.out.println("接受的修改信息:" + business);
        boolean b = businessService.updateById(business);

        return b?R.success("信息修改成功"):R.error("信息修改失败");
    }

    /**
     * 商家退出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        //清理Session中保存的当前登录员工的id
        request.getSession().removeAttribute("business");
        return R.success("退出成功");
    }
}
